<template>
  <div>
    <div v-if="state === 'complete' && finalSnapshot" class="max-w-2xl mx-auto space-y-6">
      <Card>
        <CardHeader class="text-center">
          <CardTitle class="flex items-center justify-center gap-2">
            <Eye class="w-6 h-6 text-green-500" />
            {{ t('attentionTest.testComplete') }}
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center space-y-4">
            <div class="text-6xl font-bold text-primary">
              {{ finalSnapshot.finalScore }}
            </div>
            <div :class="`text-xl font-semibold ${finalSnapshot.rating.color}`">
              {{ finalSnapshot.rating.text }}
            </div>
          </div>

          <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
              <div class="text-2xl font-bold text-green-600">{{ finalSnapshot.score.correct }}</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.correctClicks') }}</div>
            </div>
            <div class="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
              <div class="text-2xl font-bold text-red-600">{{ finalSnapshot.score.incorrect }}</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.incorrectClicks') }}</div>
            </div>
            <div class="text-center p-4 bg-orange-50 dark:bg-orange-950 rounded-lg">
              <div class="text-2xl font-bold text-orange-600">{{ finalSnapshot.score.missed }}</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.missedTargets') }}</div>
            </div>
            <div class="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
              <div class="text-2xl font-bold text-blue-600">{{ finalSnapshot.accuracy }}%</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.accuracy') }}</div>
            </div>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ finalSnapshot.totalTargets }}</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.totalTargets') }}</div>
              <div class="text-xs text-muted-foreground mt-1">
                {{ t('attentionTest.verification') }}: {{ finalSnapshot.score.correct + finalSnapshot.score.missed }}
              </div>
            </div>
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ finalSnapshot.totalNonTargets }}</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.nonTargets') }}</div>
              <div class="text-xs text-muted-foreground mt-1">
                {{ t('attentionTest.totalStimuli') }}: {{ finalSnapshot.stimuli.length }}
              </div>
            </div>
            <div class="text-center p-4 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ finalSnapshot.responsiveness }}%</div>
              <div class="text-sm text-muted-foreground">{{ t('attentionTest.responsivenessScore') }}</div>
              <div class="text-xs text-muted-foreground mt-1">
                {{ t('attentionTest.targetHitRate') }}
              </div>
            </div>
          </div>

          <div class="flex gap-4">
            <Button
              @click="resetTest"
              variant="outline"
              class="flex-1 border-2 border-slate-300 hover:border-green-500 hover:bg-green-50 hover:text-green-700 transition-all duration-200"
            >
              <RotateCcw class="w-4 h-4 mr-2" />
              {{ t('attentionTest.retest') }}
            </Button>
            <Button
              @click="handleComplete"
              class="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200"
            >
              {{ t('attentionTest.saveResult') }}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>

    <div v-else class="max-w-2xl mx-auto space-y-6">
      <Card v-if="state === 'testing'">
        <CardContent class="pt-6">
          <div class="flex justify-between items-center mb-4">
            <div class="flex items-center gap-4">
              <div class="flex items-center gap-2">
                <Timer class="w-4 h-4" />
                <span class="font-mono text-lg">{{ timeLeft }}s</span>
              </div>
              <Badge :variant="timeLeft > 20 ? 'secondary' : timeLeft > 10 ? 'default' : 'destructive'">
                {{ timeLeft > 20 ? t('attentionTest.timeAmple') : timeLeft > 10 ? t('attentionTest.timeWarning') : t('attentionTest.timeUrgent') }}
              </Badge>
            </div>
            <div class="flex items-center gap-4">
              <div class="text-sm text-green-600">
                <Target class="w-4 h-4 inline mr-1" />
                {{ score.correct }}
              </div>
              <div class="text-sm text-red-600">
                <AlertCircle class="w-4 h-4 inline mr-1" />
                {{ score.incorrect }}
              </div>
              <div class="text-sm text-orange-600">
                <Zap class="w-4 h-4 inline mr-1" />
                {{ score.missed }}
              </div>
            </div>
          </div>
          <Progress :model-value="((testDuration - timeLeft) / testDuration) * 100" />
        </CardContent>
      </Card>

      <Card>
        <template v-if="state === 'ready'">
          <CardHeader class="text-center">
            <CardTitle class="flex items-center justify-center gap-2">
              <Eye class="w-6 h-6 text-green-500" />
              {{ t('attentionTest.title') }}
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-6">
            <div class="text-center space-y-4">
              <p class="text-muted-foreground">
                {{ t('attentionTest.instruction', { testDuration }) }}
              </p>
              <div class="flex justify-center gap-4">
                <div class="flex items-center gap-2">
                  <div class="w-6 h-6 bg-blue-500 rounded-full"></div>
                  <span class="text-sm">{{ t('attentionTest.targetClick') }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <div class="w-6 h-6 bg-gray-400 rounded-full"></div>
                  <span class="text-sm">{{ t('attentionTest.nonTargetIgnore') }}</span>
                </div>
              </div>
            </div>
            <div class="text-center">
              <Button
                size="lg"
                @click="startTest"
                class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              >
                <Eye class="w-5 h-5 mr-2" />
                {{ t('attentionTest.startTest') }}
              </Button>
            </div>
          </CardContent>
        </template>

        <template v-if="state === 'testing'">
          <CardContent>
            <div class="relative w-full h-80 bg-muted rounded-lg overflow-hidden">
              <div class="absolute inset-4">
                <div
                  v-if="currentStimulus"
                  :class="`absolute w-15 h-15 rounded-full cursor-pointer transition-all duration-200 hover:scale-110 ${
                    currentStimulus.isTarget
                      ? 'bg-blue-500 hover:bg-blue-600'
                      : 'bg-gray-400 hover:bg-gray-500'
                  }`"
                  :style="{
                    left: `${currentStimulus.x}px`,
                    top: `${currentStimulus.y}px`,
                    width: '60px',
                    height: '60px'
                  }"
                  @click="handleStimulusClick(currentStimulus)"
                />
              </div>

              <div class="absolute top-4 left-4 right-4 text-center">
                <p class="text-sm text-muted-foreground bg-background/80 px-3 py-1 rounded">
                  {{ t('attentionTest.clickBlueOnly') }}
                </p>
              </div>
            </div>

            <div class="grid grid-cols-4 gap-4 mt-4">
              <div class="text-center p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                <div class="text-lg font-bold text-green-600">{{ score.correct }}</div>
                <div class="text-xs text-muted-foreground">{{ t('attentionTest.correct') }}</div>
              </div>
              <div class="text-center p-3 bg-red-50 dark:bg-red-950 rounded-lg">
                <div class="text-lg font-bold text-red-600">{{ score.incorrect }}</div>
                <div class="text-xs text-muted-foreground">{{ t('attentionTest.incorrect') }}</div>
              </div>
              <div class="text-center p-3 bg-orange-50 dark:bg-orange-950 rounded-lg">
                <div class="text-lg font-bold text-orange-600">{{ score.missed }}</div>
                <div class="text-xs text-muted-foreground">{{ t('attentionTest.missed') }}</div>
              </div>
              <div class="text-center p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div class="text-lg font-bold text-blue-600">{{ getAccuracy() }}%</div>
                <div class="text-xs text-muted-foreground">{{ t('attentionTest.accuracy') }}</div>
              </div>
            </div>

            <div class="mt-2 text-xs text-muted-foreground text-center">
              {{ t('attentionTest.targetCount') }}: {{ stimuli.filter(s => s.isTarget).length }} |
              {{ t('attentionTest.processed') }}: {{ score.correct + score.missed }} |
              {{ t('attentionTest.totalStimuliShort') }}: {{ stimuli.length }}
            </div>
          </CardContent>
        </template>
      </Card>

      <Card>
        <CardContent class="pt-6">
          <h3 class="font-semibold mb-2">{{ t('attentionTest.testInstructionsTitle') }}</h3>
          <ul class="text-sm text-muted-foreground space-y-1">
            <li>{{ t('attentionTest.instruction1', { testDuration }) }}</li>
            <li>{{ t('attentionTest.instruction2') }}</li>
            <li>{{ t('attentionTest.instruction3') }}</li>
            <li>{{ t('attentionTest.instruction4') }}</li>
            <li>{{ t('attentionTest.instruction5') }}</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Eye, Timer, Target, RotateCcw, Zap, AlertCircle } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  onComplete: {
    type: Function,
    required: true
  }
})

const { t } = useI18n();

const state = ref('ready')
const stimuli = ref([])
const timeLeft = ref(30)
const score = ref({ correct: 0, incorrect: 0, missed: 0 })
const currentStimulus = ref(null)
const testStartTime = ref(0)
const finalSnapshot = ref(null)

const gameIntervalRef = ref(null)
const timerIntervalRef = ref(null)
const allTimeoutsRef = ref(new Set())
const stateRef = ref('ready')

const testDuration = 30
const stimulusInterval = 1500
const stimulusDuration = 1000
const targetProbability = 0.3

onMounted(() => {
  stateRef.value = state.value
})

onUnmounted(() => {
  clearAllTimers()
})

watch(state, (newVal) => {
  stateRef.value = newVal
})

const clearAllTimers = () => {
  if (gameIntervalRef.value) {
    clearInterval(gameIntervalRef.value)
    gameIntervalRef.value = null
  }
  if (timerIntervalRef.value) {
    clearInterval(timerIntervalRef.value)
    timerIntervalRef.value = null
  }
  allTimeoutsRef.value.forEach(timeoutId => clearTimeout(timeoutId))
  allTimeoutsRef.value.clear()
}

const generateStimulus = () => {
  if (stateRef.value !== 'testing') return

  const containerWidth = 400
  const containerHeight = 300
  const stimulusSize = 60

  const stimulusId = Date.now() + Math.random()

  const stimulus = {
    id: stimulusId,
    x: Math.random() * (containerWidth - stimulusSize),
    y: Math.random() * (containerHeight - stimulusSize),
    isTarget: Math.random() < targetProbability,
    clicked: false
  }

  const timeoutId = setTimeout(() => {
    if (stateRef.value !== 'testing') {
      allTimeoutsRef.value.delete(timeoutId)
      return
    }

    currentStimulus.value = currentStimulus.value?.id === stimulus.id ? null : currentStimulus.value

    stimuli.value = stimuli.value.map(s => {
      if (s.id === stimulus.id && s.isTarget && !s.clicked) {
        if (stateRef.value === 'testing') {
          score.value = {
            ...score.value,
            missed: score.value.missed + 1
          }
        }
        return { ...s, isCorrect: false }
      }
      return s
    })

    allTimeoutsRef.value.delete(timeoutId)
  }, stimulusDuration)

  allTimeoutsRef.value.add(timeoutId)

  const stimulusWithTimeout = { ...stimulus, timeoutId }

  currentStimulus.value = stimulusWithTimeout
  stimuli.value = [...stimuli.value, stimulusWithTimeout]
}

const startTest = () => {
  clearAllTimers();

  // 重置所有状态
  state.value = 'testing';
  timeLeft.value = testDuration;
  score.value = { correct: 0, incorrect: 0, missed: 0 };
  stimuli.value = [];
  currentStimulus.value = null;
  testStartTime.value = Date.now();

  // 使用requestAnimationFrame替代setTimeout(50)确保UI就绪
  requestAnimationFrame(() => {
    // 倒计时逻辑（直接修改值，避免函数式更新）
    const timer = setInterval(() => {
      if (timeLeft.value <= 1) {
        clearInterval(timer);
        state.value = 'complete';
        timeLeft.value = 0;
      } else {
        timeLeft.value--;
      }
    }, 1000);
    timerIntervalRef.value = timer;

    // 刺激生成逻辑
    const game = setInterval(() => {
      generateStimulus();
    }, stimulusInterval);
    gameIntervalRef.value = game;

    // 立即生成第一个刺激
    generateStimulus();
  });
};
const handleStimulusClick = (stimulus) => {
  if (stateRef.value !== 'testing' || stimulus.clicked) return

  if (stimulus.timeoutId) {
    clearTimeout(stimulus.timeoutId)
    allTimeoutsRef.value.delete(stimulus.timeoutId)
  }

  const isCorrect = stimulus.isTarget

  stimuli.value = stimuli.value.map(s =>
    s.id === stimulus.id
      ? { ...s, clicked: true, isCorrect, timeoutId: undefined }
      : s
  )

  if (isCorrect) {
    score.value = { ...score.value, correct: score.value.correct + 1 }
  } else {
    score.value = { ...score.value, incorrect: score.value.incorrect + 1 }
  }

  currentStimulus.value = currentStimulus.value?.id === stimulus.id ? null : currentStimulus.value
}

const resetTest = () => {
  clearAllTimers()

  state.value = 'ready'
  timeLeft.value = testDuration
  score.value = { correct: 0, incorrect: 0, missed: 0 }
  stimuli.value = []
  currentStimulus.value = null
  testStartTime.value = 0
  finalSnapshot.value = null
}

const getAccuracy = () => {
  const total = score.value.correct + score.value.incorrect + score.value.missed
  if (total === 0) return 0
  const accuracy = (score.value.correct / total) * 100
  return Math.round(isNaN(accuracy) ? 0 : Math.max(0, Math.min(100, accuracy)))
}

const getReactionSpeed = () => {
  const totalTargets = score.value.correct + score.value.missed
  if (totalTargets === 0) return 0
  const responsiveness = (score.value.correct / totalTargets) * 100
  return Math.round(isNaN(responsiveness) ? 0 : Math.max(0, Math.min(100, responsiveness)))
}

const getFinalScore = () => {
  const accuracy = getAccuracy()
  const responsiveness = getReactionSpeed()
  const totalTargets = stimuli.value.filter(s => s.isTarget).length
  const completionBonus = totalTargets > 15 ? 10 : 0

  const baseScore = (accuracy * 0.6 + responsiveness * 0.4)
  const finalScore = baseScore + completionBonus
  return Math.round(isNaN(finalScore) ? 0 : Math.max(0, Math.min(100, finalScore)))
}

const getRating = () => {
  const finalScore = getFinalScore()
  if (finalScore >= 90) return { text: '注意力专家', color: 'text-yellow-500' }
  if (finalScore >= 80) return { text: '优秀', color: 'text-green-500' }
  if (finalScore >= 70) return { text: '良好', color: 'text-blue-500' }
  if (finalScore >= 60) return { text: '一般', color: 'text-gray-500' }
  return { text: '需要提高', color: 'text-orange-500' }
}

const handleComplete = () => {
  if (!finalSnapshot.value) return

  const result = {
    id: Date.now().toString(),
    testType: 'attention',
    score: finalSnapshot.value.finalScore,
    completedAt: new Date(),
    duration: Math.max(1, finalSnapshot.value.totalTestTime),
    details: {
      accuracy: finalSnapshot.value.accuracy,
      responsiveness: finalSnapshot.value.responsiveness,
      correctClicks: finalSnapshot.value.score.correct,
      incorrectClicks: finalSnapshot.value.score.incorrect,
      missedTargets: finalSnapshot.value.score.missed,
      totalTargets: finalSnapshot.value.totalTargets,
      totalNonTargets: finalSnapshot.value.totalNonTargets,
      totalStimuli: finalSnapshot.value.stimuli.length,
      rating: finalSnapshot.value.rating.text,
      testDuration: testDuration,

      totalQuestions: finalSnapshot.value.stimuli.length,
      correctAnswers: finalSnapshot.value.score.correct,
      averageTimePerQuestion: finalSnapshot.value.stimuli.length > 0 ? Math.round(finalSnapshot.value.totalTestTime / finalSnapshot.value.stimuli.length) : 0,

      averageTime: finalSnapshot.value.totalTestTime,
      totalRounds: finalSnapshot.value.stimuli.length,
      difficulty: 'medium',

      targetHitRate: finalSnapshot.value.totalTargets > 0 ? Math.round((finalSnapshot.value.score.correct / finalSnapshot.value.totalTargets) * 100) : 0,
      falseAlarmRate: finalSnapshot.value.totalNonTargets > 0 ? Math.round((finalSnapshot.value.score.incorrect / finalSnapshot.value.totalNonTargets) * 100) : 0,
      missRate: finalSnapshot.value.totalTargets > 0 ? Math.round((finalSnapshot.value.score.missed / finalSnapshot.value.totalTargets) * 100) : 0
    }
  }
  props.onComplete(result)
}

watch(() => state.value, (newState) => {
  if (newState === 'complete' && !finalSnapshot.value) {
    clearAllTimers()

    let processedScore = { ...score.value }
    let processedStimuli = [...stimuli.value]

    processedStimuli = processedStimuli.map(stimulus => {
      if (stimulus.isTarget && !stimulus.clicked && stimulus.isCorrect === undefined) {
        processedScore.missed += 1
        return { ...stimulus, isCorrect: false }
      }
      return stimulus
    })

    if (currentStimulus.value && currentStimulus.value.isTarget && !currentStimulus.value.clicked) {
      const stimulusExists = processedStimuli.some(s => s.id === currentStimulus.value.id)
      if (!stimulusExists) {
        processedStimuli.push({ ...currentStimulus.value, isCorrect: false })
        processedScore.missed += 1
      }
    }

    const currentTestTime = testStartTime.value > 0 ? Math.round((Date.now() - testStartTime.value) / 1000) : testDuration
    const allTargetStimuli = processedStimuli.filter(s => s.isTarget)
    const allNonTargetStimuli = processedStimuli.filter(s => !s.isTarget)

    const actualTargetCount = allTargetStimuli.length
    const processedTargetCount = processedScore.correct + processedScore.missed

    if (actualTargetCount > processedTargetCount) {
      const missingTargets = actualTargetCount - processedTargetCount
      processedScore.missed += missingTargets
    }

    const total = processedScore.correct + processedScore.incorrect + processedScore.missed
    const accuracy = total === 0 ? 0 : Math.round(Math.max(0, Math.min(100, (processedScore.correct / total) * 100)))
    const totalTargets = processedScore.correct + processedScore.missed
    const responsiveness = totalTargets === 0 ? 0 : Math.round(Math.max(0, Math.min(100, (processedScore.correct / totalTargets) * 100)))
    const completionBonus = actualTargetCount > 15 ? 10 : 0
    const baseScore = (accuracy * 0.6 + responsiveness * 0.4)
    const finalScore = Math.round(Math.max(0, Math.min(100, baseScore + completionBonus)))

    let rating
    if (finalScore >= 90) rating = { text: 'Attention Expert', color: 'text-yellow-500' }
    else if (finalScore >= 80) rating = { text: 'Excellent', color: 'text-green-500' }
    else if (finalScore >= 70) rating = { text: 'Good', color: 'text-blue-500' }
    else if (finalScore >= 60) rating = { text: 'Average', color: 'text-gray-500' }
    else rating = { text: 'Needs Improvement', color: 'text-orange-500' }

    finalSnapshot.value = {
      finalScore,
      accuracy,
      responsiveness,
      totalTestTime: currentTestTime,
      totalTargets: actualTargetCount,
      totalNonTargets: allNonTargetStimuli.length,
      score: processedScore,
      stimuli: processedStimuli,
      rating
    }

    score.value = processedScore
    stimuli.value = processedStimuli
  }
})
</script>